package com.jintian.smart.base.expression.fn;

import com.jintian.smart.base.api.system.provider.IEmployeeProvider;
import com.jintian.smart.kernel.common.context.ContextHolder;
import com.jintian.smart.kernel.common.util.StringUtil;
import com.jintian.smart.kernel.core.annotation.beetl.BeetlFunction;
import org.apache.dubbo.config.annotation.DubboReference;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.sql.clazz.kit.BeetlSQLException;

@BeetlFunction(code = "childAreaCondition")
public class ChildAreaConditionFunction implements Function {
    @DubboReference(check = false)
    private IEmployeeProvider employeeProvider;

    @Override
    public Object call(Object[] paras, Context ctx) {
        String areaCode = "";
        if (paras.length == 2) {
            areaCode = (String) paras[1];
        }
        // todo 地区尚未支持
//        if (StringUtil.isEmpty(areaCode) && StringUtil.isNotEmpty(ContextHolder.getUserId())) {
//            areaCode = employeeProvider.getById(ContextHolder.getUserId()).getAreaCode();
//        }
        if (StringUtil.isEmpty(areaCode)) {
            throw new BeetlSQLException(BeetlSQLException.QUERY_CONDITION_ERROR, "childAreaCondition中无法获取areaCode");
        }
        if (areaCode.length() < 6) {
            throw new IllegalArgumentException("areaCode=" + areaCode + ",长度小于6");
        }
        if ("0000".equals(areaCode.substring(2, 6))) {
            // 省级用户
            return paras[0] + " like '" + areaCode.substring(0, 2) + "%'";
        } else if ("00".equals(areaCode.substring(4, 6))) {
            // 市级用户
            return paras[0] + " like '" + areaCode.substring(0, 4) + "%'";
        } else {
            // 区县或乡镇
            return paras[0] + " like '" + areaCode + "%'";
        }
    }
}
